package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.PageDomain;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.ElderFamilyBindingDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.FamilyMemberListVo;
import com.zzyl.nursing.vo.IndicatorDataVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.zzyl.common.utils.PageUtils.startPage;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private FamilyMemberElderServiceImpl familyMemberElderService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IoTDAClient client;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }


    /**
     * 老人家属绑定
     *
     * @param dto
     */
    @Override
    public void FamilyBinding(ElderFamilyBindingDto dto) {
        //根据身份证号与姓名查询老人
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getIdCard()).eq(Elder::getStatus, 1).eq(Elder::getName, dto.getName()));
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("该老人不存在或状态异常");
        }
        //获取登录用户id
        Long userId = UserThreadLocal.getUserId();

        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(dto.getRemark());
        familyMemberElderService.save(familyMemberElder);
    }

    @Override
    public List<FamilyMemberElderVo> FamilyList() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> list = familyMemberElderService.list(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        ArrayList<Long> FamilyMemberIds = new ArrayList<>();
        for (FamilyMemberElder familyMemberElder : list) {
            FamilyMemberIds.add(familyMemberElder.getElderId());
        }
        List<Elder> ElderLists = elderService.list(Wrappers.<Elder>lambdaQuery().in(Elder::getId, FamilyMemberIds));


        List<FamilyMemberElderVo> familyMemberElderVos = new ArrayList<>();
        for (Elder elder : ElderLists) {
            FamilyMemberElderVo familyMemberElderVo = new FamilyMemberElderVo();
            familyMemberElderVo.setId(elder.getId());
            familyMemberElderVo.setFamilyMemberId(userId);
            familyMemberElderVo.setElderName(elder.getName());
            familyMemberElderVo.setElderId(elder.getId());
            familyMemberElderVos.add(familyMemberElderVo);
        }

        return familyMemberElderVos;

    }

    @Override
    public List<FamilyMemberListVo> FamilyListByPage(PageDomain pageDomain) {
        //获取登录用户id
        Long userId = UserThreadLocal.getUserId();
        //分页
        startPage();
        List<FamilyMemberListVo> familyMemberListVos = familyMemberMapper.FamilyListByPage(userId);
        return familyMemberListVos;
    }

    @Override
    public List<Map<String, Object>> queryServicePropertiesById(String iotId) {
        String o = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        List<Map> list = JSONUtil.toList(o, Map.class);
        list.removeIf(item -> !"HeartRate".equals(item.get("functionId")));
        System.out.println(list);
        if (list.isEmpty()) {
            return new ArrayList<>();
        }
        Map<String, Object> map = list.get(0);
        List<Map<String, Object>> list1 = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map.put("functionId", "HeartRate");
        map.put("eventTime", map.get("eventTime"));
        map.put("value", map.get("dataValue"));
        list1.add(map);

        return list1;

    }

    @Override
    public List<IndicatorDataVo> queryDeviceDataListByDay(DeviceDataDto dto) {
        //1. 获取原始数据
        DeviceData deviceData = BeanUtil.copyProperties(dto, DeviceData.class);
        //时间格式转换
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = formatter.format(dto.getStartTime());
        String endTimeStr = formatter.format(dto.getEndTime());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(startTimeStr, dateTimeFormatter);
        LocalDateTime endTime = LocalDateTime.parse(endTimeStr, dateTimeFormatter);
        List<IndicatorDataVo> deviceDataList = deviceDataMapper.queryDeviceDataListByDay(deviceData.getIotId(), deviceData.getFunctionId(), startTime, endTime);
        // 1. 先获取当天的完整小时列表（0-23）
        List<Integer> allHours = IntStream.rangeClosed(0, 23)
                .boxed()
                .collect(Collectors.toList());

        // 2. 执行原始聚合逻辑（保留你的原始代码）
        Map<Integer, Double> hourlyAvgMap = deviceDataList.stream()
                .collect(Collectors.groupingBy(
                        d -> d.getDateTime().getHour(),
                        Collectors.averagingDouble(d ->
                                d.getDataValue() != null ? d.getDataValue() : 0.0
                        )
                ));

        // 3. 合并完整小时列表和聚合结果（核心补全逻辑）
        Map<Integer, Double> fullHourlyData = allHours.stream()
                .collect(Collectors.toMap(
                        hour -> hour,
                        hour -> hourlyAvgMap.getOrDefault(hour, 0.0) // 存在值用原值，否则用0
                ));

        // 4. 转换为最终结果列表
        List<IndicatorDataVo> collect = fullHourlyData.entrySet().stream()
                .map(entry -> {
                    IndicatorDataVo data = new IndicatorDataVo();
                    // 格式化时间为 "yyyy-MM-dd HH:00:00"
                    String timeStr = String.format("%04d-%02d-%02d %02d:00:00",
                            startTime.getYear(),
                            startTime.getMonthValue(),
                            startTime.getDayOfMonth(),
                            entry.getKey()
                    );
                    data.setDateTime(LocalDateTime.parse(timeStr, dateTimeFormatter));
                    data.setDataValue(entry.getValue());
                    return data;
                })
                .collect(Collectors.toList());

//        System.out.println(collect);
//        System.out.println(deviceDataList);

        return collect;


    }

    @Override
    public List<IndicatorDataVo> queryDeviceDataListByWeek(DeviceDataDto dto) {
        //1. 获取原始数据
        DeviceData deviceData = BeanUtil.copyProperties(dto, DeviceData.class);
        //时间格式转换
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = formatter.format(dto.getStartTime());
        String endTimeStr = formatter.format(dto.getEndTime());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(startTimeStr, dateTimeFormatter);
        LocalDateTime endTime = LocalDateTime.parse(endTimeStr, dateTimeFormatter);
        List<IndicatorDataVo> deviceDataList = deviceDataMapper.queryDeviceDataListByDay(deviceData.getIotId(), deviceData.getFunctionId(), startTime, endTime);

        System.out.println(deviceDataList);
        // 1. 计算前7天的起止日期（包含今天，共7天）
        LocalDate today = endTime.toLocalDate();
        LocalDate startOfPeriod = today.minusDays(6); // 前7天起始日期（包含今天）
        LocalDate endOfPeriod = today;

        // 2. 过滤本周数据并执行聚合（按LocalDate分组）
        Map<LocalDate, Double> dayAvgMap = deviceDataList.stream()
                .filter(d ->
                        !d.getDateTime().toLocalDate().isBefore(startOfPeriod) &&  // 过滤前7天数据
                                !d.getDateTime().toLocalDate().isAfter(endOfPeriod)
                )
                .collect(Collectors.groupingBy(
                        d -> d.getDateTime().toLocalDate(),  // 按LocalDate分组
                        Collectors.averagingDouble(d ->
                                d.getDataValue() != null ? d.getDataValue() : 0.0
                        )
                ));

        // 3. 生成前7天所有日期列表
        List<LocalDate> allDatesInPeriod = startOfPeriod.datesUntil(endOfPeriod.plusDays(1))
                .collect(Collectors.toList());

        // 4. 合并完整周期数据（核心补全逻辑）
        Map<LocalDate, Double> fullPeriodData = allDatesInPeriod.stream()
                .collect(Collectors.toMap(
                        date -> date,
                        date -> dayAvgMap.getOrDefault(date, 0.0) // 存在值用原值，否则用0
                ));

        // 5. 转换为最终结果列表（已包含排序）
        List<IndicatorDataVo> collect = fullPeriodData.entrySet().stream()
                .map(entry -> {
                    IndicatorDataVo data = new IndicatorDataVo();
                    // 设置日期为当天00:00:00
                    data.setDateTime(entry.getKey().atStartOfDay());
                    data.setDataValue(entry.getValue());
                    return data;
                })
                .sorted(Comparator.comparing(IndicatorDataVo::getDateTime)) // 按时间升序排序
                .collect(Collectors.toList());

        return collect;
    }

}
